#include "client_gets_file.h"


off_t get_reallen(int fd)
{
    off_t offsize = 0;
    char cmp = 0;
    while(read(fd, &cmp, 1) != -1 && cmp != '\0') {
        offsize++;
    }
    printf("real length = %ld\n", offsize);
    return offsize;
    
}

int recvCircle(int fd,char*buff,int length)
{
    char *pbuf=buff;
    int left=length;
    int ret=0;
    while(left>0)
    {
        ret=recv(fd, pbuf, length,MSG_WAITALL);
        if(ret==-1&&errno==EINTR)
        {
            continue;
        }
        else if(ret==0)
        {
            close(fd);
            break;
        }else if(ret==-1)
        {
            perror("recv");
            break;
        }
        else
        {
            pbuf+=ret;
            left-=ret;
        }
    }
    return length-left;
}
void recv_file(int clientfd)
{
     //先接查找文件消息
     char fileinfo[100]={0};
     int infolen=0;
     //接受信息长度
     recvCircle(clientfd,(char*)&infolen,4);
     //接受信息内容
     recvCircle(clientfd,fileinfo,infolen);
     printf("%s\n",fileinfo);
     if(strcmp(fileinfo,"server haven't the file，please try again")==0)
     {
         return ;
     }
     //接文件名
     char filename[100]={0};
     //recv第三个参数最多能接1000个字节数据
     //先接受文件名，文件名长度
     int length=0;
     recvCircle(clientfd,(char*)&length,4);
     printf("filenaem length:%d\n",length);
     recvCircle(clientfd,filename,length);
     printf("filename:%s\n",filename);
  
     int fd=open(filename,O_RDWR|O_CREAT,0664);
     //int seeklen = lseek(fd, 0, SEEK_END);
     //printf("lseek = %d\n", seeklen);

     //struct stat statbuf;//statbuffer
     //memset(&statbuf, 0, sizeof(statbuf));//初始化为空
     //int ret = fstat(fd, &statbuf);//读取当前文件的信息
     //ERROR_CHECK(ret, -1, "fstat");
     //printf("localfilelen = %ld\n", statbuf.st_size);
     //lseek(fd, 0, SEEK_END);//偏移到文件结尾
     int ret = 0;
     off_t localfilelen = get_reallen(fd);
     ret = send(clientfd, &localfilelen, sizeof(off_t), 0);//向服务端发送 本地文件长度
     //2.再接收文件
     //先接收文件长度
     off_t filelen=0;
     recvCircle(clientfd,(char *)&filelen,8);
     printf("file length:%ld\n",filelen);
  
     ftruncate(fd,filelen);//一定不能少
     char *p=(char*)mmap(NULL,filelen,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
     filelen -= localfilelen;
     recvCircle(clientfd, p + localfilelen, filelen);
     printf("file:%s done\n", filename);
     munmap(p,filelen);
     close(fd);
     return;
}
